package othello.logic;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import othello.UI.GameFrame;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import othello.UI.dialogs.SetupGameDialog;

/*
 * @author sa11
 * Kör en spelsession i taget.
 */
public class Othello {

    private GameFrame frame = new GameFrame();
    private GameManager gm;
    private SetupGameDialog sgd = new SetupGameDialog(frame);

    public void startOthello() throws IOException {

        while (true) {
            sgd.setVisible(true);
            gm = new GameManager(sgd.getPlayer1(), sgd.getPlayer2());
            //Kollar om testläge ska köras(ai vs ai)
            if (sgd.getTestMode()) {
                frame.setSpeed(0);
                testComp();
                sgd.setTestMode(false);
            } else {
                //Kör ett normalt spel
                frame.setSpeed(1000);
                gm.gameplay(frame, false);
            }
        }
    }

    /*
     * Testläge som kör en ai mot en annan ai ett antal gånger. Räknar samman resultatet och redovisar det i en dialog.
     */
    private void testComp() {
        int times = 10000;
        JLabel jlbThinking = new JLabel("");
        jlbThinking.setIcon(new ImageIcon("gfx/thinking.gif"));
        JProgressBar jprBar = new JProgressBar();
        JDialog jdlDialog = new JDialog();
        jdlDialog.setTitle("Thinking...");
        JLabel jlbInfo = new JLabel("Running " + times + " games to see which AI is best.");
        jdlDialog.add(jprBar, BorderLayout.SOUTH);
        jdlDialog.add(jlbThinking, BorderLayout.CENTER);
        jdlDialog.add(jlbInfo, BorderLayout.NORTH);
        jdlDialog.pack();
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        int height = screenSize.height;
        int width = screenSize.width;
        jdlDialog.setLocation(width / 2 - jdlDialog.getWidth() / 2, height / 2 - jdlDialog.getHeight() / 2);
        jdlDialog.setVisible(true);

        double p1 = 0, p2 = 0, d = 0;
        jprBar.setMaximum(times);
        jprBar.setMinimum(0);
        for (int i = 0; i < times; i++) {
            jprBar.setValue(i);
            int result = gm.gameplay(frame, true);
            if (result == 1) {
                p1++;
            }
            if (result == 2) {
                p2++;
            }
            if (result == 0) {
                d++;
            }
        }
        jdlDialog.dispose();
        JOptionPane.showMessageDialog(null, "<html>" + sgd.getPlayer1().getName() + ": " + p1 / (times) * 100 + "% <br>" + sgd.getPlayer2().getName() + ": " + p2 / (times) * 100 + "% <br>Draw: " + d / (p1 + p2 + d) * 100 + "%", "Resultat", JOptionPane.INFORMATION_MESSAGE);

    }
}
